package com.app.art.security;

import com.app.art.properties.IgnoreUrlsProperties;
import com.app.art.utils.jwt.JwtClaims;
import com.app.art.utils.jwt.JwtTokenUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT登录授权过滤器
 * Created by macro on 2018/4/26.
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private IgnoreUrlsProperties ignoreUrlsProperties;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("doFilterInternal >> {} ", request.getRequestURI());
        if (shouldSkip(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        log.info("shouldSkip false >> {} ", request.getRequestURI());
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            // 获取token
            String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
            // 获取真实token
            JwtClaims userNameFromToken = jwtTokenUtil.validateAndParseToken(authToken);
            LOGGER.info("checking username:{}", userNameFromToken);
            if (userNameFromToken != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(userNameFromToken.getUsername());
                if (userDetails != null) {
                    // 认证成功 创建认证AuthenticationToken
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    LOGGER.info("authenticated user:{}", userDetails);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 判断当前请求是否应跳过 JWT 认证
     */
    private boolean shouldSkip(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        // 跳过 OPTIONS 请求（CORS 预检）
        if (requestURI.equals("/") || request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }

        // 检查配置的忽略路径
        for (String pattern : ignoreUrlsProperties.getUrls()) {
            if (pathMatcher.match(pattern, requestURI)) {
                return true;
            }
        }
        return false;
    }

}
